<template>
    <div>
        <NuxtLayout name="default">
            <template #panel> </template>
            <ElScrollbar>
                <div class="text-center m-auto max-w-[600px]">
                    <h2
                        class="online-skill-title pb-[24px] pt-[6px] px-[24px] font-bold text-center leading-[1.1] break-all text-[38px] mt-16"
                    >
                        请200+专家帮忙
                    </h2>
                    <div class="relative">
                        <i
                            style="line-height: 38px; font-size: 20px"
                            class="iconfont icon-fasong absolute z-10 text-[#2454FF] cursor-pointer right-[0px]"
                        />
                        <el-input
                            v-model="keyword"
                            size="large"
                            style="
                                box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.05);
                                transform: scale(1.05);
                            "
                            placeholder="搜索专家或直接AI对话"
                            @keydown="handleInputEnter"
                        />
                    </div>
                    <div class="text-[#838a95] mt-5 mb-10">
                        <el-popover>
                            <div>这是图片</div>
                            <template #reference>
                                <span>
                                    <i
                                        class="iconfont icon-douyin"
                                    />关注抖音更新
                                </span>
                            </template>
                        </el-popover>
                        <span>
                            <i class="iconfont icon-douyin ml-8" />
                            提交你的需求
                        </span>
                    </div>
                </div>
                <div
                    class="online-skill-page-max-w max-w-[1520px] m-auto w-[90%] min-w-[1100px]"
                >
                    <template v-if="keyword">
                        <SkillList
                            :skills="skillFilter"
                            @collection="getSidebarList"
                            @selected="handleselected"
                        />
                        <el-empty v-if="!skillFilter.length" />
                    </template>
                    <template v-else>
                        <ul class="flex mt-2 flex-wrap justify-center mb-5">
                            <li
                                @click="activeCategory = ''"
                                :class="{
                                    'active-category': activeCategory === ''
                                }"
                                class="tab flex-shrink-0 cursor-pointer bg-white text-gray-DEEP mb-3"
                            >
                                全部
                            </li>
                            <li
                                @click="activeCategory = 'mine'"
                                :class="{
                                    'active-category': activeCategory === 'mine'
                                }"
                                class="tab flex-shrink-0 cursor-pointer bg-white text-gray-DEEP mb-3"
                            >
                                我的
                            </li>
                            <li
                                v-for="i in sidebarList"
                                :key="i.id"
                                @click="activeCategory = i.id"
                                class="tab flex-shrink-0 cursor-pointer bg-white text-gray-DEEP mb-3"
                                :class="{
                                    'active-category': activeCategory === i.id
                                }"
                            >
                                {{ i.name }}
                            </li>
                        </ul>
                        <div
                            v-for="item in sidebarList.filter((f) =>
                                activeCategory ? f.id === activeCategory : true
                            )"
                            :key="item.id"
                        >
                            <h3
                                class="online-skill-category-title mt-[8px] mb-[14px] font-bold flex items-center text-[18px]"
                            >
                                {{ item.name }}
                            </h3>
                            <SkillList
                                :skills="item.skill"
                                @collection="getSidebarList"
                                @selected="handleselected"
                            />
                        </div>
                        <el-empty v-if="!sidebarList.length" />
                    </template>
                </div>
            </ElScrollbar>
        </NuxtLayout>
    </div>
</template>
<script setup lang="ts">
import { ElInput } from 'element-plus'
import { getSkillList } from '@/api/skill'
import { getchatLog, cleanChat, chatSendText } from '@/api/chat'
import { useUserStore } from '~~/stores/user'

import feedback from '~~/utils/feedback'
import { watchDebounced } from '@vueuse/core'
const router = useRouter()
const userStore = useUserStore()
//当前选中的侧边栏
const selectval = ref(0)
//聊天框标题
const chatTitle = ref('')
const currentIcon = ref('')
//侧边栏列表
const sidebarList = ref([])

// 选中的技能类型
const activeCategory = ref('')
// 输入框的关键字
const keyword = ref()

const skillFilter = computed(() => {
    if (!keyword.value) {
        return []
    }
    const _keyword = keyword.value.toLowerCase()
    console.log(_keyword)
    // 筛选顶部类型和输入框内容
    return sidebarList.value
        .filter((f) => {
            return f.skill.length
        })
        .map((m) => {
            return m.skill
        })
        .flat()
        .filter((f) => {
            const target = f.name + f.describe + f.content || ''
            return target.toLowerCase()?.includes(_keyword)
        })
})

//选择侧边栏列表
const handleselected = ({ id, title, image, name }: any) => {
    const _data = {
        selectval: id,
        chatTitle: title,
        name,
        currentIcon: image,
        chatType: 3
    }
    // 跳转到首页并且选择某个skill
    sessionStorage.setItem('skill', JSON.stringify(_data))

    router.push('/')

    // chatContentList.value = []
    // selectval.value = id
    // chatTitle.value = title
    // currentIcon.value = image
    // nextTick(async () => {
    //     await getChatList()
    //     chattingRef.value.scrollToBottom()
    // })
}
// const guidedPopupRef = shallowRef()
//对话记录列表
// const chatContentList: any = ref([])
//对话框ref
// const chattingRef = ref(null)
//侧边栏列表数据
const getSidebarList = async () => {
    sidebarList.value = await getSkillList({
        user_id: userStore.userInfo?.id
    })
}

// //获取聊天记录
// const getChatList = async () => {
//     const data = await getchatLog({ type: 3, other_id: selectval.value })
//     if (data != null) chatContentList.value = data
// }
//获取聊天记录
// const getChatList = async () => {
//     let data = await getchatLog({
//         type: 3,
//         other_id: selectval.value,
//         page_type: 0
//     })
//     data = data?.lists.map((item: any) => {
//         if (item.type == 1) {
//             return { ...item, from_avatar: userStore.userInfo.avatar }
//         } else {
//             return { ...item, from_avatar: currentIcon.value }
//         }
//     })
//     chatContentList.value = data
// }
//发送问题

// const isReceiving = ref(false)
// const contentPost = async (userInput: any, model?: string) => {
//     try {
//         isReceiving.value = true
//         chatContentList.value.push({
//             type: 1,
//             content: userInput,
//             from_avatar: userStore.userInfo.avatar
//         })
//         chatContentList.value.push({
//             type: 2,
//             loading: true,
//             content: [],
//             from_avatar: currentIcon.value,
//             id: ''
//         })
//         await chatSendText(
//             {
//                 model: model,
//                 question: userInput,
//                 type: 3,
//                 other_id: selectval.value
//             },
//             {
//                 onstart(reader) {
//                     streamReader = reader
//                 },
//                 onmessage(value) {
//                     value
//                         .trim()
//                         .split('data:')
//                         .forEach(async (text) => {
//                             if (text !== '') {
//                                 try {
//                                     const dataJson = JSON.parse(text)
//                                     const {
//                                         id: chatId,
//                                         event,
//                                         data,
//                                         code,
//                                         index
//                                     } = dataJson
//
//                                     if (event == 'error' && code === 101) {
//                                         guidedPopupRef.value?.open()
//                                     } else if (event == 'error') {
//                                         feedback.msgError(data)
//                                     }
//
//                                     let chatIndex =
//                                         chatContentList.value.findIndex(
//                                             (item) => item.id === chatId
//                                         )
//                                     if (chatIndex === -1) {
//                                         chatIndex =
//                                             chatContentList.value.length - 1
//
//                                         chatContentList.value[chatIndex].id =
//                                             chatId
//                                     }
//
//                                     if (data) {
//                                         if (
//                                             !chatContentList.value[chatIndex]
//                                                 .content[index]
//                                         ) {
//                                             chatContentList.value[
//                                                 chatIndex
//                                             ].content[index] = ''
//                                         }
//                                         chatContentList.value[
//                                             chatIndex
//                                         ].content[index] += data
//                                     }
//
//                                     if (event === 'finish') {
//                                         chatContentList.value[
//                                             chatIndex
//                                         ].loading = false
//                                         return
//                                     }
//                                 } catch (error) {}
//                             }
//                         })
//                 },
//                 onclose() {
//                     isReceiving.value = false
//                     setTimeout(getChatList, 400)
//                 }
//             }
//         )
//         chattingRef.value.cleanInput()
//     } catch (error) {
//         isReceiving.value = false
//         chatContentList.value.splice(chatContentList.value.length - 2, 2)
//     }
//     nextTick(() => {
//         chattingRef.value.scrollToBottom()
//     })
// }

// let streamReader: ReadableStreamDefaultReader<Uint8Array> | null = null
// const chatClose = (index?: number) => {
//     streamReader?.cancel()
//     if (index) {
//         chatContentList.value[index].loading = false
//     }
//     isReceiving.value = false
// }

//清空会话
// const cleanChatLog = async () => {
//     await feedback.confirm('确定清空对话？')
//     await cleanChat({ type: 3, other_id: selectval.value })
//     chatContentList.value = []
// }

//选择侧边栏列表第一个选项
// const selectFirst = () => {
//     handleselected(sidebarList.value[0].skill[0])
// }
const handleInputEnter = (e) => {
    if (e.keyCode === 13) {
        // enter 跳转兴博士ai 并且发送消息
        sessionStorage.setItem('autoSendMsg', keyword.value)
        router.push('/')
    }
}

onMounted(async () => {
    await getSidebarList()
    // selectFirst()
})

// watchDebounced(
//     keyword,
//     (value) => {
//         getSidebarList()
//     },
//     {
//         debounce: 500
//     }
// )

definePageMeta({
    layout: false
})
</script>
<style lang="scss" scoped>
@import 'assets/styles/fix_online_css.scss';

.active-category {
    color: white !important;
    background: var(--el-color-primary);
}
.tab {
    margin-right: 14px;
    padding: 0 16px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    border-radius: 6px;
    color: #838a95;
    transition: all 0.4s;
}
.actived {
    border-left: 3px solid var(--el-color-primary);
}
.unactived {
    border-left: 3px solid #f8f8f8;
}
</style>
